//
//  LXLoginViewController.m
//  LvXi_newVersion
//
//  Created by 诸葛孔明 on 16/8/9.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "LXLoginViewController.h"
#import "UIView+LxViewFrame.h"

#import "Toast.h"

@interface LXLoginViewController ()<TencentSessionDelegate,TCAPIRequestDelegate,TencentLoginDelegate,WXApiManagerDelegate,WXApiDelegate,UITextFieldDelegate>{
    TencentOAuth *_tencentOAuth;
    NSArray* _permissions;
    BOOL        _isSocial;
    NSString *  _socialId;
    NSString *  _socailType;
    NSString *  _socailNickName;
    NSString *  _socailHeaderImage;
}


@property (weak, nonatomic) IBOutlet UIButton *closeButton;

/*****************登录界面*****************/
//登录整体界面
@property (weak, nonatomic) IBOutlet UIView *loginView;
//用户名
@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
//密码
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
//忘记密码按钮
@property (weak, nonatomic) IBOutlet UIButton *forgetPwdBtn;
//快速注册按钮
@property (weak, nonatomic) IBOutlet UIButton *quicklyRegistBtn;
//登录按钮
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftSpace;

//第三方登录底部约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *thirdLoginBottomConstraint;
//用户名顶部约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *userNameViewTopConstrain;
//logo顶部约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoTopContstraint;

//**********************************************我是分割线*************************************************//
//**********************************************我是分割线*************************************************//

/*****************找回密码界面*****************/
//找回密码整体界面
@property (weak, nonatomic) IBOutlet UIView *findPwd;
//手机号
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
//验证码
@property (weak, nonatomic) IBOutlet UITextField *chectWordTextField;
//获取按钮
@property (weak, nonatomic) IBOutlet UIButton *getBtn;
//设置新密码
@property (weak, nonatomic) IBOutlet UITextField *settingPwdTextField;
//找回按钮
@property (weak, nonatomic) IBOutlet UIButton *findBtn;
//快速登录按钮
@property (weak, nonatomic) IBOutlet UIButton *quickLoginBtn;
//找回密码右边约束

//**********************************************我是分割线*************************************************//
//**********************************************我是分割线*************************************************//

/*****************注册界面*****************/
@property (weak, nonatomic) IBOutlet UITextField *regist_phone;
@property (weak, nonatomic) IBOutlet UITextField *regist_check;
@property (weak, nonatomic) IBOutlet UITextField *regist_name;
@property (weak, nonatomic) IBOutlet UITextField *regist_pwd;
@property (weak, nonatomic) IBOutlet UIButton *regist_btn;
//获取
@property (weak, nonatomic) IBOutlet UIButton *regist_getBtn;


@end

@implementation LXLoginViewController
-(void)awakeFromNib{
    [super awakeFromNib];
    self.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    _isSocial = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isSocial = NO;
    [self setUpButtonBorder];
    
    if (ScreenWidth == 320) {
        self.thirdLoginBottomConstraint.constant = 20;
        self.userNameViewTopConstrain.constant = 20;
        self.logoTopContstraint.constant = 120;
    }
    
    self.userNameTextField.text = User_mobile;
    _permissions = [NSArray arrayWithObjects: kOPEN_PERMISSION_GET_USER_INFO,
                            kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                            kOPEN_PERMISSION_ADD_SHARE,kOPEN_PERMISSION_GET_INFO,
                            nil];
    _tencentOAuth =
    [[TencentOAuth alloc] initWithAppId:Tencent_AppID andDelegate:self];
    [WXApiManager sharedManager].delegate = self;

}

//统一设置按钮边框
- (void)setUpButtonBorder
{
    self.closeButton.layer.cornerRadius = self.closeButton.width * 0.5;
    
    self.loginButton.layer.borderWidth = 1;
    self.loginButton.layer.borderColor = [UIColor clearColor].CGColor;
    self.loginButton.layer.cornerRadius = 5;
    [self.loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.loginButton setBackgroundColor:LXMainColor];
    
    self.findBtn.layer.borderColor = [UIColor clearColor].CGColor;
    self.findBtn.layer.borderWidth = 1;
    self.findBtn.layer.cornerRadius = 5;
    [self.findBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.findBtn setBackgroundColor:LXMainColor];
    
    self.getBtn.layer.cornerRadius = 5;
    self.getBtn.layer.borderColor = [UIColor clearColor].CGColor;
    [self.getBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.getBtn setBackgroundColor:LXMainColor];
    
    self.regist_btn.layer.borderColor = [UIColor clearColor].CGColor;
    self.regist_btn.layer.borderWidth = 1;
    self.regist_btn.layer.cornerRadius = 5;
    [self.regist_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.regist_btn setBackgroundColor:LXMainColor];
    
    self.regist_getBtn.layer.borderColor = [UIColor clearColor].CGColor;
    self.regist_getBtn.layer.borderWidth = 1;
    self.regist_getBtn.layer.cornerRadius = 5;
    [self.regist_getBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.regist_getBtn setBackgroundColor:LXMainColor];
}

/*****************登录界面*****************/

#pragma mark - 关闭按钮点击
- (IBAction)closeBtnClick {
    if(self.closeCallBack)self.closeCallBack();
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - 登录按钮点击
- (IBAction)loginButtonClick {

    
    if(self.userNameTextField.text.length==0){
        [self.view alertWithTitle:@"登录失败" mesege:@"用户名不能为空" buttons:@[@"知道了"] handle:nil];
        return;
    }
    if(self.pwdTextField.text==0){
        [self.view alertWithTitle:@"登录失败" mesege:@"密码不能为空" buttons:@[@"知道了"] handle:nil];
        return;
    }
    NSDictionary * prama = @{
                             @"loginname":self.userNameTextField.text,
                             @"password":self.pwdTextField.text,
                             };
    [[LXDataManager manager] userLoginWithPrama:prama complete:^(BOOL success, id res) {
        if(success){
            [self.view alertWithTitle:@"" mesege:@"登录成功" buttons:@[@"确定"] handle:^(NSInteger buttonIndex) {
                [self dismissViewControllerAnimated:NO completion:^{
                    [[self getCurrentVC].navigationController popToRootViewControllerAnimated:YES];
                }];
            }];
            
        }else{
            [self.view alertWithTitle:@"登录失败,用户不存在或密码错误" mesege:@"" buttons:@[@"确定"] handle:nil];
        }
    }];
     
}
#pragma mark - 忘记密码按钮点击
- (IBAction)forgetPwdBtnClick {
    self.leftSpace.constant = self.view.width;
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}
#pragma mark - 快速注册按钮点击
- (IBAction)quicklyRegistBtnClick {
    self.leftSpace.constant = - self.view.width;
    if(_isSocial){
        self.regist_name.userInteractionEnabled = NO;
        self.regist_name.placeholder = @"第三方注册暂时不用填写昵称";
    }else{
        self.regist_name.userInteractionEnabled = YES;
        self.regist_name.placeholder = @"昵称";
    }
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    }];
}
#pragma - mark  微信登录
- (IBAction)wechatLogin {
    SendAuthReq * req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    req.state = @"com.shanjuetang.LVXI139";
    req.openID = WeiXin_AppKey;
    [WXApi sendAuthReq:req viewController:self delegate:[WXApiManager sharedManager]];

}

#pragma mark - 微信登录回调
-(void)managerDidRecvAuthResponse:(SendAuthResp *)response{
    WeakSelf(ws);
    __block NSString * get_access_token_url =  [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WeiXin_AppKey,WeiXin_AppSecret,response.code];
    
    __block NSString * getinfoUrl;
    __block  NSDictionary * access_token_dict;
    __block  NSDictionary * user_info_dict;
    
    dispatch_queue_t queue = dispatch_queue_create("get user info", NULL);
    
    dispatch_async(queue, ^{
        NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:get_access_token_url]];
        access_token_dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        getinfoUrl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token_dict[@"access_token"],access_token_dict[@"openid"]];
        
    });
    
    dispatch_async(queue, ^{
        NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:getinfoUrl]];
        user_info_dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

    });
    
    dispatch_async(queue, ^{
        _isSocial = YES;
        _socialId = user_info_dict[@"openid"];
        _socailType = @"weixin";
        _socailNickName =user_info_dict[@"nickname"];
        _socailHeaderImage = user_info_dict[@"headimgurl"];
//        user.nickname = user_info_dict[@"nickname"];
//        user.headerImage = user_info_dict[@"headimgurl"];
//        user.weixinid = user_info_dict[@"openid"];
//        [self dismissViewControllerAnimated:YES completion:^{
//            
//        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            [[LXDataManager manager] userSocialLogin:@{@"type":_socailType,@"social_id":_socialId} complete:^(BOOL success, id res) {
                if(success){
                    [LXUser upDataUserInfoWith:res[@"data"][@"user"]];
                    [self _updateUserInfo];
                    [Toast showWithMessege:@"登录成功" duration:2 hiddenComplete:^{
                        [ws dismissViewControllerAnimated:YES completion:nil];
                    }];
                }else{
                    [Toast showWithMessege:@"账户未绑定手机，请绑定" duration:2 hiddenComplete:^{
                        [self quicklyRegistBtnClick];
                    }];
                }
            }];

        });
    });
}

//微博登录
- (IBAction)weiboLogin {
    NSLog(@"%s",__func__);
}


#pragma mark -  qq登录
- (IBAction)qqLogin {
    NSLog(@"%s",__func__);
    [_tencentOAuth authorize:_permissions];
}


-(void)getUserInfoResponse:(APIResponse *)response{
    if(LoginState){
        _socailNickName     = response.jsonResponse[@"nickname"];
        _socailHeaderImage  = response.jsonResponse[@"figureurl_qq_2"];
        [self _updateUserInfo];
    }
}

-(void)_updateUserInfo{
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    param[@"nickname"] = _socailNickName;
    param[@"headerImage"] = _socailHeaderImage;
    [LXUser upDataUserInfoWith:param];
}

-(void)tencentDidLogin{
    [_tencentOAuth getUserInfo];
    WeakSelf(ws);
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    param[@"type"] = @"qq";
    param[@"social_id"] = [_tencentOAuth openId];
    [[LXDataManager manager] userSocialLogin:param complete:^(BOOL success, id res) {
        if(success){
            [LXUser upDataUserInfoWith:res[@"data"][@"user"]];
            [Toast showWithMessege:@"登录成功" duration:2 hiddenComplete:^{
                if(ws.closeCallBack)ws.closeCallBack();
                [ws dismissViewControllerAnimated:YES completion:nil];
            }];
        }else{
            _isSocial   = YES;
            _socailType = @"qq";
            _socialId   = [_tencentOAuth openId];
            [Toast showWithMessege:@"账户未绑定手机，请绑定" duration:2 hiddenComplete:^{
                [self quicklyRegistBtnClick];
            }];
        }
    }];
}

-(void)tencentDidNotLogin:(BOOL)cancelled{
    NSLog(@"%s",__func__);
}

-(void)tencentDidNotNetWork{
    NSLog(@"%s",__func__);
}


//*********************我是分割线*********************//
//*********************我是分割线*********************//
/*****************找回密码界面*****************/
#pragma mark - 找回按钮点击
- (IBAction)findBtnClick {
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    NSString * mobileKey = @"mobile";
    NSString * passwordKey = @"password";
    NSString * captchaKey = @"code";
    NSString * mobileValue = self.phoneTextField.text;
    NSString * passwordValue = self.settingPwdTextField.text;
    NSString * captchaValue = self.chectWordTextField.text;
    if(mobileValue.length==0){
        [self.view alertWithTitle:@"找回失败" mesege:@"手机号不能为空" buttons:@[@"知道了"] handle:nil];
        return;
    }
    if(captchaValue.length!=6){
        [self.view alertWithTitle:@"找回失败" mesege:@"验证码应为6位数字" buttons:@[@"知道了"] handle:nil];
        return;
    }
    if(passwordValue.length==0){
        [self.view alertWithTitle:@"找回失败" mesege:@"新密码不能为空" buttons:@[@"知道了"] handle:nil];
        return;
    }
    param[mobileKey] = mobileValue;
    param[captchaKey] = captchaValue;
    param[passwordKey] = passwordValue;
    
    
    [[LXDataManager manager] forgetPasswordWithPrama:param complete:^(BOOL success, id res) {
        if(success){
            [Toast showWithMessege:[self handleMsg:res[@"data"][@"error"]] distanceToBotton:150 duration:2 hiddenComplete:^{
                [self quickLoginBtnClick];
            }];
        }else{
            [Toast showWithMessege:[self handleMsg:res[@"data"][@"error"]] distanceToBotton:150 duration:2 hiddenComplete:nil];
        }
    }];
}
#pragma mark - 获取验证码按钮点击
- (IBAction)getBtnClick {
    
    
    NSString * mobileValue ;
    NSString * smsUrl;
    if(self.findPwd.x == 0){
        mobileValue = self.phoneTextField.text ;
        smsUrl = ForgetPasswordGetCodeAPI;
    }else{
        mobileValue = self.regist_phone.text ;
        smsUrl = GetSmsCodeAPI;
    }
    if(mobileValue.length==0){
        
        [self.view alertWithTitle:@"获取失败" mesege:@"手机号不能为空" buttons:@[@"知道了"] handle:nil];
        return;
    }
    
    
    //MARK:这里要吐槽下后台了。。。
    //MARK:找回密码发送验证码
    if(self.findPwd.x == 0){
     [[NetRequest request] GetWithUrl:smsUrl prama:@{@"mobile":mobileValue} requestHandle:^(BOOL success, id responseDict) {
         if(success){
             [Toast showWithMessege:@"验证码已经发送，请注意查收!" distanceToBotton:150 duration:2 hiddenComplete:nil];
         }else{
             [Toast showWithMessege:@"验证失败，手机号不存在或格式错误" distanceToBotton:150 duration:2 hiddenComplete:nil];
         }
     }];
        
        
    //MARK:注册发送验证码
    }else{
        [[NetRequest request] PostWithUrl:smsUrl prama:@{@"mobile":mobileValue} requestHandle:^(BOOL success, id responseDict) {
            if(success){
                [Toast showWithMessege:@"验证码已经发送，请注意查收!" distanceToBotton:150 duration:2 hiddenComplete:nil];
            }else{
                [Toast showWithMessege:@"验证失败，手机号不存在或格式错误" distanceToBotton:150 duration:2 hiddenComplete:nil];
            }
        }];
    }
    
    


    
}
//MARK:快速登录按钮点击
- (IBAction)quickLoginBtnClick {
    self.leftSpace.constant = 0;
    _isSocial = NO;
    _socailHeaderImage = @"";
    _socailNickName = @"";
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - /*****************注册界面*****************/
//MARK:注册按钮点击
- (IBAction)registBtnClick {
    NSString * mobileKey = @"mobile";
    NSString * passwordKey = @"password";
    NSString * captchaKey = @"captcha";
    NSString * nickNameKey = @"nickname";
    NSString * mobileValue = self.regist_phone.text;
    NSString * passwordValue = self.regist_pwd.text;
    NSString * captchaValue = self.regist_check.text;
    NSString * nickNameValue = self.regist_name.text;
    if(mobileValue.length==0){
        [self.view alertWithTitle:@"注册失败" mesege:@"手机号不能为空" buttons:@[@"知道了"] handle:nil];
        return;
    }
    if(passwordValue.length==0){
        [self.view alertWithTitle:@"注册失败" mesege:@"密码不能为空" buttons:@[@"知道了"] handle:nil];
        return;
    }
    if(captchaValue.length==0){
        [self.view alertWithTitle:@"注册失败" mesege:@"验证码不能为空" buttons:@[@"知道了"] handle:nil];
        return;
    }
    NSMutableDictionary * prama = [NSMutableDictionary dictionary];
    prama[mobileKey] = mobileValue;
    prama[passwordKey] = passwordValue;
    prama[captchaKey] = captchaValue;
    if(nickNameValue.length!=0){
        prama[nickNameKey] = nickNameValue;
    }
    
    if(!_isSocial){
        
    }else{
        prama[@"password2"] = passwordValue;
        prama[@"type"] = _socailType;
        prama[@"social_id"] = _socialId;
    }
    
    [[LXDataManager manager] userRegisterWithPrama:prama complete:^(BOOL success, id res) {
        if(success){
            [self _updateUserInfo];
            [self.view alertWithTitle:@"" mesege:@"注册成功" buttons:@[@"知道了"] handle:^(NSInteger buttonIndex) {
                if(self.closeCallBack) self.closeCallBack();
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
        }else{
            [self.view alertWithTitle:@"" mesege:[self handleMsg:res[@"msg"]] buttons:@[@"确定"] handle:^(NSInteger buttonIndex) {
            }];
        }
    }];
    
    
    
}

-(NSString*)handleMsg:(id)msg{
    if([msg isKindOfClass:[NSArray class]]){
        return [msg componentsJoinedByString:@"\n"];
    }
    if([msg isKindOfClass:[NSString class]]){
        return msg;
    }
    return @"错误";
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
@end
